﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BabyToys.Models;
using System.Web.Helpers;
using System.IO;
using System.Text.RegularExpressions;
using PagedList.Mvc;
using PagedList;
using System.Data;
namespace BabyToys.Controllers
{
    public class AdminSanPhamController : Controller
    {
        //
        // GET: /AdminSanPham/
        DatabaseContext db = new DatabaseContext();
        public ActionResult Index()
        {
            return View();
        }
        #region Xai chung
        public List<DanhMucDropdownListItem> DropdownListDanhMuc()
        {
            List<DanhMucDropdownListItem> danhmucs = new List<DanhMucDropdownListItem>();
            foreach (var danhmuc in db.DanhMucs.Where(d => d.DanhMucCha.IdDanhMuc == null))
            {
                danhmucs.Add(new DanhMucDropdownListItem { Value = danhmuc.IdDanhMuc, Text = danhmuc.TenDanhMuc });
                string prefix = "";
                LayDanhMuc(danhmucs, danhmuc.IdDanhMuc,prefix);
            }
            return danhmucs;
        }
        public void LayDanhMuc(List<DanhMucDropdownListItem> danhmucs,int id,string prefix)
        {
            var dsdanhmuc = db.DanhMucs.Where(d => d.DanhMucCha.IdDanhMuc == id);
            string tmp_prefix = prefix;
            if (dsdanhmuc != null)
            {
                foreach (var danhmuc in dsdanhmuc)
                {
                    string text = tmp_prefix + "----" + danhmuc.TenDanhMuc;
                    danhmucs.Add(new DanhMucDropdownListItem { Value = danhmuc.IdDanhMuc, Text = text });
                    prefix += "----";
                    LayDanhMuc(danhmucs, danhmuc.IdDanhMuc,prefix);
                }
            }
        }
        public void LoadSanPham(int id, List<SanPham> sanphams)
        {
            var dsdanhmuc = db.DanhMucs.Where(d => d.DanhMucCha.IdDanhMuc == id);
            if (dsdanhmuc != null)
            {
                foreach (var danhmuc in dsdanhmuc)
                {
                    var dssanpham = db.SanPhams.Where(b => b.IdDanhMuc == danhmuc.IdDanhMuc);
                    if (dssanpham != null)
                    {
                        foreach (var bv in dssanpham)
                        {
                            sanphams.Add(bv);
                        }
                    }
                    LoadSanPham(danhmuc.IdDanhMuc, sanphams);
                }
            }
        }
        public ActionResult CapNhatHienThi(int id, bool hienthi)
        {
            if (Models.User.CurrentUser.Quyen.HasPermission("xoa_san_pham"))
            {
                var sanpham = db.SanPhams.SingleOrDefault(s => s.IdSanPham == id);
                sanpham.HienThi = hienthi;
                db.Entry(sanpham).State = EntityState.Modified;
                db.SaveChanges();
                return View();
            }
            //TempData["ThongBao"] = "<script>$( document ).ready(function(){ alert('Bạn không có quyền thực hiện chức này!') })</script>";
            return RedirectToAction("Error","Admin");
        }
        public void LuuChiTietAnh(SanPham sanpham, int number)
        {
            for (int i = 0; i < number; i++)
            {
                var image = WebImage.GetImageFromRequest("anh " + i);
                if (image != null)
                {
                    string ImageName = Path.GetFileName(image.FileName);
                    ImageName = "main"+DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day +
                        DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + "-" +
                        "-" + (i + 1) + "-" + ImageName;
                    var pathToSave = Path.Combine(Server.MapPath("~/Content/Images/SanPham"), ImageName);
                    image.Save(pathToSave);

                    string thumbnail = "thumbnail-" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day +
                        DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + "-" + ImageName;
                    var pathToSaveThumbnail = Path.Combine(Server.MapPath("~/Content/Images/SanPham"), thumbnail);
                    image.Resize(250, 250, true, true);
                    image.Save(pathToSaveThumbnail);
                    HinhAnh hinh = new HinhAnh { SanPham = sanpham, AnhGoc = ImageName, Thumbnail = thumbnail };
                    db.HinhAnhs.Add(hinh);
                    db.SaveChanges();
                }
            }
        }
        
        #endregion

        #region 1.Danh sach
        public ActionResult DanhSach(int? page, int? HienThi, int? SapXep, string currentFilter, string searchString, int? IdDanhMuc, int? IdThuongHieu)
        {
            if(Models.User.CurrentUser.Quyen.HasPermission("xem_san_pham"))
            {
                List<SanPham> dssanphams = new List<SanPham>();
                var sanphams = from s in db.SanPhams
                               where s.IdDanhMuc == IdDanhMuc
                               select s;
                ViewBag.Count = db.SanPhams.Count();
                foreach (var sp in sanphams)
                {
                    dssanphams.Add(sp);
                }

                LoadSanPham(IdDanhMuc ?? 1, dssanphams);
                if (searchString != null)
                {
                    page = 1;
                }
                else
                {
                    searchString = currentFilter;
                }

                ViewBag.CurrentFilter = searchString;
                if (!String.IsNullOrEmpty(searchString))
                {
                    dssanphams = dssanphams.Where(s => s.TenSP.Contains(searchString)).ToList();
                    //ViewBag.TenSanPham = TenSanPham;
                }
                if (!String.IsNullOrEmpty(IdThuongHieu.ToString()))
                {
                    dssanphams = dssanphams.Where(s => s.IdThuongHieu == IdThuongHieu).ToList();
                }
                //dssanphams = dssanphams.Where(s => s.IdDanhMuc == IdDanhMuc).ToList();
                dssanphams = dssanphams.OrderByDescending(s => s.IdSanPham).ToList();
                switch (SapXep ?? 0)
                {
                    case 0: break;
                    case 1:
                        dssanphams = dssanphams.OrderBy(s => s.Giaban).ToList();
                        break;
                    case 2:
                        dssanphams = dssanphams.OrderByDescending(s => s.Giaban).ToList();
                        break;
                    case 3:
                        dssanphams = dssanphams.OrderBy(s => s.TenSP).ToList();
                        break;
                    case 4:
                        dssanphams = dssanphams.OrderByDescending(s => s.TenSP).ToList();
                        break;
                    default:
                        break;
                }
                var pageNumber = page ?? 1;
                ViewBag.IdDanhMuc = new SelectList(DropdownListDanhMuc(), "Value", "Text");
                ViewBag.IdThuongHieu = new SelectList(db.ThuongHieus.ToList(), "IdThuongHieu", "TenThuongHieu");
                ViewBag.onePageOfProduct = dssanphams.ToPagedList(pageNumber, HienThi ?? 10);
                ViewBag.HienThi = HienThi ?? 10;
                ViewBag.SapXep = SapXep ?? 0;
                ViewBag.DanhMuc = IdDanhMuc;
                ViewBag.ThuongHieu = IdThuongHieu;
                ViewBag.ThongBao = TempData["ThongBao"];
                if (Models.User.CurrentUser.Quyen.HasPermission("xoa_san_pham"))
                {
                    ViewBag.Xoa = true;
                }
                return View();
            }
            return RedirectToAction("Error","Admin");
        }
        #endregion

        #region 2.Sua
        public ActionResult Sua(int id = 0)
        {
            if (Models.User.CurrentUser.Quyen.HasPermission("sua_san_pham"))
            {
                var sanpham = db.SanPhams.SingleOrDefault(s => s.IdSanPham == id);
                ViewBag.HinhAnh = db.HinhAnhs.ToList().Where(h => h.SanPham == sanpham);
                ViewBag.SoHinhCoTheUp = 10 - (db.HinhAnhs.ToList().Where(h => h.SanPham == sanpham).Count());
                ViewBag.IdDanhMuc = new SelectList(DropdownListDanhMuc(), "Value", "Text", sanpham.IdDanhMuc);
                ViewBag.IdThuongHieu = new SelectList(db.ThuongHieus.ToList(), "IdThuongHieu", "TenThuongHieu", sanpham.IdDanhMuc);
                return View(sanpham);
            }
            return RedirectToAction("Error","Admin");
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Sua(SanPham sanpham, string sua)
        {
            if ("Upload".Equals(sua, StringComparison.OrdinalIgnoreCase))
            {
                //LuuChiTietAnh(sanpham,(10 - (db.HinhAnhs.ToList().Where(h => h.SanPham == sanpham).Count())));
                var sp = db.SanPhams.SingleOrDefault(s => s.IdSanPham == sanpham.IdSanPham);
                LuuChiTietAnh(sp, (10 - (db.HinhAnhs.ToList().Where(h => h.SanPham == sp).Count())));
                ViewBag.HinhAnh = db.HinhAnhs.ToList().Where(h => h.SanPham == sp);
                ViewBag.SoHinhCoTheUp = 10 - (db.HinhAnhs.ToList().Where(h => h.SanPham == sp).Count());
                ViewBag.IdDanhMuc = new SelectList(DropdownListDanhMuc(), "Value", "Text", sanpham.IdDanhMuc);
                ViewBag.IdThuongHieu = new SelectList(db.ThuongHieus.ToList(), "IdThuongHieu", "TenThuongHieu", sanpham.IdDanhMuc);
                return View(sanpham);
            }
            if (ModelState.IsValid)
            {
                var image = WebImage.GetImageFromRequest("anhdaidien");
                if (image != null)
                {
                    string ImageName = Path.GetFileName(image.FileName);
                    //anh goc
                    ImageName = DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day +
                            DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + "-" + ImageName;
                    var pathToSave = Path.Combine(Server.MapPath("~/Content/Images/SanPham"), ImageName);
                    image.Save(pathToSave);
                    sanpham.HinhDaiDien = ImageName;
                    //thumbnail
                    ImageName = "thumbnail-" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day +
                            DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + "-"+ ImageName;
                    var pathToSaveThumbnail = Path.Combine(Server.MapPath("~/Content/Images/SanPham"), ImageName);
                    image.Resize(250, 250, true, true);
                    image.Save(pathToSaveThumbnail);
                    sanpham.Thumbnail = ImageName;
                }
                db.Entry(sanpham).State = EntityState.Unchanged;
                db.Entry(sanpham).State = EntityState.Modified;
                db.SaveChanges();
                if ("Lưu và thoát".Equals(sua, StringComparison.OrdinalIgnoreCase))
                {
                    return RedirectToAction("DanhSach");
                }
                if ("Lưu và tiếp tục".Equals(sua, StringComparison.OrdinalIgnoreCase))
                {
                    return RedirectToAction("Sua", new { id=sanpham.IdSanPham });
                }
             }
            
            ViewBag.HinhAnh = db.HinhAnhs.ToList().Where(h => h.SanPham == sanpham);
            ViewBag.SoHinhCoTheUp = 10 - (db.HinhAnhs.ToList().Where(h => h.SanPham == sanpham).Count());
            ViewBag.IdDanhMuc = new SelectList(DropdownListDanhMuc(), "Value", "Text", sanpham.IdDanhMuc);
            ViewBag.IdThuongHieu = new SelectList(db.ThuongHieus.ToList(), "IdThuongHieu", "TenThuongHieu", sanpham.IdDanhMuc);
            return View(sanpham);
        }
        #endregion

        #region 3.Them Moi
        public ActionResult ThemMoi()
        {
            //User selected=Models.User.CurrentUser
            if(Models.User.CurrentUser.Quyen.HasPermission("them_san_pham"))
            {
                ViewBag.IdDanhMuc = new SelectList(DropdownListDanhMuc(), "Value", "Text");
                ViewBag.IdThuongHieu = new SelectList(db.ThuongHieus.ToList(), "IdThuongHieu", "TenThuongHieu");
                return View();
            }
            return RedirectToAction("Error","Admin");
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ThemMoi(SanPham sanpham,string luu)
        {
            if (ModelState.IsValid)
            {
                var image = WebImage.GetImageFromRequest("anhdaidien");
                if (image != null)
                {
                    string ImageName = Path.GetFileName(image.FileName);

                    //anh goc
                    ImageName = "main" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day +
                        DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + "-" + ImageName;
                    var pathToSave = Path.Combine(Server.MapPath("~/Content/Images/SanPham"), ImageName);
                    image.Save(pathToSave);
                    sanpham.HinhDaiDien = ImageName;
                    //thumbnail/
                    ImageName = "thumbnail-" + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day +
                        DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + "-" + ImageName;
                    var pathToSaveThumbnail = Path.Combine(Server.MapPath("~/Content/Images/SanPham"), ImageName);
                    image.Resize(250, 250, true, true);
                    image.Save(pathToSaveThumbnail);
                    sanpham.Thumbnail = ImageName;
                }
                else
                {
                    sanpham.HinhDaiDien = "noimageyet.jpg";
                    sanpham.Thumbnail = "thumb-noimageyet.jpg"; 
                }
                db.SanPhams.Add(sanpham);
                db.SaveChanges();
                LuuChiTietAnh(sanpham, 10);
                if ("Lưu và đóng".Equals(luu, StringComparison.OrdinalIgnoreCase))
                {
                    return RedirectToAction("DanhSach");
                }
                if ("Lưu và tạo mới".Equals(luu, StringComparison.OrdinalIgnoreCase))
                {
                    return RedirectToAction("ThemMoi");
                }
            }
            ViewBag.IdThuongHieu = new SelectList(db.ThuongHieus.ToList(), "IdThuongHieu", "TenThuongHieu");
            ViewBag.IdDanhMuc = new SelectList(DropdownListDanhMuc(), "Value", "Text");
            return View(sanpham);
        }
        #endregion

        #region 4.Xoa
        
        //public ActionResult Xoa(int id)
        //{
        //    if (Models.User.CurrentUser.Quyen.HasPermission("xoa_san_pham"))
        //    {
        //        var sanpham = db.SanPhams.SingleOrDefault(s => s.IdSanPham == id);
        //        if (sanpham != null)
        //        {
        //            XoaSanPham(sanpham);
        //        }
        //        TempData["ThongBao"] = "<script>$( document ).ready(function(){ alert('Xóa thành công!') })</script>";
        //        return RedirectToAction("DanhSach");
        //    }
        //    return RedirectToAction("Error","Admin");
        //}
        //[HttpPost, ActionName("DanhSach")]
        //public ActionResult XoaNhieuSanPham(int[] deleteInputs, int? HienThi, int? page)
        //{
        //    if (Models.User.CurrentUser.Quyen.HasPermission("xoa_san_pham"))
        //    {
        //        if (deleteInputs != null)
        //        {
        //            foreach (var item in deleteInputs)
        //            {
        //                var sanpham = db.SanPhams.SingleOrDefault(s => s.IdSanPham == item);
        //                XoaSanPham(sanpham);
        //            }
        //            TempData["ThongBao"] = "<script>$( document ).ready(function(){ alert('Xóa thành công!') })</script>";
        //            return RedirectToAction("DanhSach");
        //        }
        //        TempData["ThongBao"] = "<script>$( document ).ready(function(){ alert('Bạn chưa chọn sản phẩm!') })</script>";
        //        return RedirectToAction("DanhSach");
        //    }
        //    return RedirectToAction("Error", "Admin"); 
        //}
        //public void XoaSanPham(SanPham sanpham)
        //{
        //    var hinhanhs = db.HinhAnhs.ToList().Where(h => h.SanPham == sanpham);
        //    if (hinhanhs != null)
        //    {
        //        foreach (var hinhanh in hinhanhs)
        //        {
        //            string anhgoc = hinhanh.AnhGoc;
        //            XoaAnhTrongThuMuc(anhgoc);
        //            string thumbnail = hinhanh.Thumbnail;
        //            XoaAnhTrongThuMuc(thumbnail);
                    
        //            db.HinhAnhs.Remove(hinhanh);
        //            db.SaveChanges();
        //        }
        //    }
            
        //    string hinhdaidien = sanpham.HinhDaiDien;
        //    XoaAnhTrongThuMuc(hinhdaidien);
        //    string thumbnailsp = sanpham.Thumbnail;
        //    XoaAnhTrongThuMuc(thumbnailsp);

        //    db.SanPhams.Remove(sanpham);
        //    db.SaveChanges();
        //}
        public ActionResult XoaAnh(int id, int IdSanPham)
        {
            var hinhanh = db.HinhAnhs.SingleOrDefault(h => h.ID == id);
            string anhgoc = hinhanh.AnhGoc;
            XoaAnhTrongThuMuc(anhgoc);
            string thumbnail = hinhanh.Thumbnail;
            XoaAnhTrongThuMuc(thumbnail);
            db.HinhAnhs.Remove(hinhanh);
            db.SaveChanges();
            //XoaAnhTrongThuMuc(
            return RedirectToAction("Sua", new { id = IdSanPham });
        }
        public void XoaAnhTrongThuMuc(string name)
        {
            if (!String.IsNullOrEmpty(name))
            {
                var path = Path.Combine(Server.MapPath("~/Content/Images/SanPham"), name);
                if (System.IO.File.Exists(path))
                {
                    System.IO.File.Delete(path);
                }
            }
        }
        #endregion

        [NonAction]
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            User su = (User)Session["admin"];
            if (su == null)
            {
                filterContext.Result = new RedirectResult("~/AdminLogin");
            }
            else
            {
                Models.User.CurrentUser = su;
            }
            base.OnActionExecuting(filterContext);
        }
        
    }
}
